{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "# 使用块的网络（VGG）\n",
    ":label:`sec_vgg`\n",
    "\n",
    "虽然 AlexNet 证明深层神经网络卓有成效，但它没有提供一个通用的模板来指导后续的研究人员设计新的网络。\n",
    "在下面的几个章节中，我们将介绍一些常用于设计深层神经网络的启发式概念。\n",
    "\n",
    "与芯片设计中工程师从放置晶体管到逻辑元件再到逻辑块的过程类似，神经网络结构的设计也逐渐变得更加抽象。研究人员开始从单个神经元的角度思考问题，发展到整个层次，现在又转向模块，重复各层的模式。\n",
    "\n",
    "使用块的想法首先出现在牛津大学的 [视觉几何组（visualgeometry Group）](http://www.robots.ox.ac.uk/~vgg/) (VGG)的 *VGG网络* 中。通过使用循环和子程序，可以很容易地在任何现代深度学习框架的代码中实现这些重复的结构。\n",
    "\n",
    "## (**VGG块**)\n",
    "\n",
    "经典卷积神经网络的基本组成部分是下面的这个序列：\n",
    "1. 带填充以保持分辨率的卷积层；\n",
    "1. 非线性激活函数，如ReLU；\n",
    "1. 池化层，如最大池化层。\n",
    "\n",
    "而一个 VGG 块与之类似，由一系列卷积层组成，后面再加上用于空间下采样的最大池化层。在最初的 VGG 论文 :cite:`Simonyan.Zisserman.2014` 中，作者使用了带有 $3\\times3$ 卷积核、填充为 1（保持高度和宽度）的卷积层，和带有 $2 \\times 2$ 池化窗口、步幅为 2（每个块后的分辨率减半）的最大池化层。在下面的代码中，我们定义了一个名为 `vgg_block` 的函数来实现一个 VGG 块。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "该函数有三个参数，分别对应于卷积层的数量 `num_convs`、输入通道的数量 `in_channels`\n",
    "和输出通道的数量  `out_channels`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import paddle\n",
    "import paddle.nn as nn\n",
    "\n",
    "def vgg_block(num_convs, in_channels, out_channels):\n",
    "    layers = []\n",
    "    for _ in range(num_convs):\n",
    "        layers.append(\n",
    "            nn.Conv2D(in_channels, out_channels, kernel_size=3, padding=1))\n",
    "        layers.append(nn.ReLU())\n",
    "        in_channels = out_channels\n",
    "    layers.append(nn.MaxPool2D(kernel_size=2, stride=2))\n",
    "    return nn.Sequential(*layers)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## [**VGG网络**]\n",
    "\n",
    "与 AlexNet、LeNet 一样，VGG 网络可以分为两部分：第一部分主要由卷积层和池化层组成，第二部分由全连接层组成。如 :numref:`fig_vgg` 中所示。\n",
    "\n",
    "![从AlexNet到VGG，它们本质上都是块设计。](../img/vgg.svg)\n",
    ":width:`400px`\n",
    ":label:`fig_vgg`\n",
    "\n",
    "\n",
    "VGG神经网络连续连接 :numref:`fig_vgg` 的几个 VGG 块（在 `vgg_block` 函数中定义）。其中有超参数变量 `conv_arch` 。该变量指定了每个VGG块里卷积层个数和输出通道数。全连接模块则与AlexNet中的相同。\n",
    "\n",
    "原始 VGG 网络有 5 个卷积块，其中前两个块各有一个卷积层，后三个块各包含两个卷积层。\n",
    "第一个模块有 64 个输出通道，每个后续模块将输出通道数量翻倍，直到该数字达到 512。由于该网络使用 8 个卷积层和 3 个全连接层，因此它通常被称为 VGG-11。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "conv_arch = ((1, 64), (1, 128), (2, 256), (2, 512), (2, 512))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "下面的代码实现了 VGG-11。可以通过在 `conv_arch` 上执行 for 循环来简单实现。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def vgg(conv_arch):\n",
    "    conv_blks = []\n",
    "    in_channels = 1\n",
    "    # 卷积层部分\n",
    "    for (num_convs, out_channels) in conv_arch:\n",
    "        conv_blks.append(vgg_block(num_convs, in_channels, out_channels))\n",
    "        in_channels = out_channels\n",
    "\n",
    "    return nn.Sequential(*conv_blks, nn.Flatten(),\n",
    "                         # 全连接层部分\n",
    "                         nn.Linear(out_channels * 7 * 7, 4096), nn.ReLU(),\n",
    "                         nn.Dropout(0.5), nn.Linear(4096, 4096), nn.ReLU(),\n",
    "                         nn.Dropout(0.5), nn.Linear(4096, 10))\n",
    "\n",
    "VGG = vgg(conv_arch)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "接下来，我们将构建一个高度和宽度为 224 的单通道数据样本，以[**观察每个层输出的形状**]。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "---------------------------------------------------------------------------\n",
      " Layer (type)       Input Shape          Output Shape         Param #    \n",
      "===========================================================================\n",
      "   Conv2D-1      [[1, 1, 224, 224]]   [1, 64, 224, 224]         640      \n",
      "    ReLU-1      [[1, 64, 224, 224]]   [1, 64, 224, 224]          0       \n",
      "  MaxPool2D-1   [[1, 64, 224, 224]]   [1, 64, 112, 112]          0       \n",
      "   Conv2D-2     [[1, 64, 112, 112]]   [1, 128, 112, 112]      73,856     \n",
      "    ReLU-2      [[1, 128, 112, 112]]  [1, 128, 112, 112]         0       \n",
      "  MaxPool2D-2   [[1, 128, 112, 112]]   [1, 128, 56, 56]          0       \n",
      "   Conv2D-3      [[1, 128, 56, 56]]    [1, 256, 56, 56]       295,168    \n",
      "    ReLU-3       [[1, 256, 56, 56]]    [1, 256, 56, 56]          0       \n",
      "   Conv2D-4      [[1, 256, 56, 56]]    [1, 256, 56, 56]       590,080    \n",
      "    ReLU-4       [[1, 256, 56, 56]]    [1, 256, 56, 56]          0       \n",
      "  MaxPool2D-3    [[1, 256, 56, 56]]    [1, 256, 28, 28]          0       \n",
      "   Conv2D-5      [[1, 256, 28, 28]]    [1, 512, 28, 28]      1,180,160   \n",
      "    ReLU-5       [[1, 512, 28, 28]]    [1, 512, 28, 28]          0       \n",
      "   Conv2D-6      [[1, 512, 28, 28]]    [1, 512, 28, 28]      2,359,808   \n",
      "    ReLU-6       [[1, 512, 28, 28]]    [1, 512, 28, 28]          0       \n",
      "  MaxPool2D-4    [[1, 512, 28, 28]]    [1, 512, 14, 14]          0       \n",
      "   Conv2D-7      [[1, 512, 14, 14]]    [1, 512, 14, 14]      2,359,808   \n",
      "    ReLU-7       [[1, 512, 14, 14]]    [1, 512, 14, 14]          0       \n",
      "   Conv2D-8      [[1, 512, 14, 14]]    [1, 512, 14, 14]      2,359,808   \n",
      "    ReLU-8       [[1, 512, 14, 14]]    [1, 512, 14, 14]          0       \n",
      "  MaxPool2D-5    [[1, 512, 14, 14]]     [1, 512, 7, 7]           0       \n",
      "   Flatten-1      [[1, 512, 7, 7]]        [1, 25088]             0       \n",
      "   Linear-1         [[1, 25088]]          [1, 4096]         102,764,544  \n",
      "    ReLU-9          [[1, 4096]]           [1, 4096]              0       \n",
      "   Dropout-1        [[1, 4096]]           [1, 4096]              0       \n",
      "   Linear-2         [[1, 4096]]           [1, 4096]         16,781,312   \n",
      "    ReLU-10         [[1, 4096]]           [1, 4096]              0       \n",
      "   Dropout-2        [[1, 4096]]           [1, 4096]              0       \n",
      "   Linear-3         [[1, 4096]]            [1, 10]            40,970     \n",
      "===========================================================================\n",
      "Total params: 128,806,154\n",
      "Trainable params: 128,806,154\n",
      "Non-trainable params: 0\n",
      "---------------------------------------------------------------------------\n",
      "Input size (MB): 0.19\n",
      "Forward/backward pass size (MB): 125.37\n",
      "Params size (MB): 491.36\n",
      "Estimated Total Size (MB): 616.92\n",
      "---------------------------------------------------------------------------\n",
      "\n",
      "{'total_params': 128806154, 'trainable_params': 128806154}\n"
     ]
    }
   ],
   "source": [
    "print(paddle.summary(VGG, (1, 1, 224, 224)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "正如你所看到的，我们在每个块的高度和宽度减半，最终高度和宽度都为7。最后再展平表示，送入全连接层处理。\n",
    "\n",
    "## 训练模型\n",
    "\n",
    "[**由于VGG-11比AlexNet计算量更大，因此我们构建了一个通道数较少的网络**]，足够用于训练Fashion-MNIST数据集。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "ratio = 4\n",
    "small_conv_arch = [(pair[0], pair[1] // ratio) for pair in conv_arch]\n",
    "VGG = vgg(small_conv_arch)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "除了使用略高的学习率外，[**模型训练**]过程与 :numref:`sec_alexnet` 中的 AlexNet 类似。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The loss value printed in the log is the current step, and the metric is the average value of previous steps.\n",
      "Epoch 1/10\n"
     ]
    }
   ],
   "source": [
    "import paddle.vision.transforms as T\n",
    "from paddle.vision.datasets import FashionMNIST\n",
    "\n",
    "lr, num_epochs, batch_size = 0.005, 10, 128\n",
    "\n",
    "# 数据集处理\n",
    "transform = T.Compose([\n",
    "    T.Resize(224),\n",
    "    T.Transpose(),\n",
    "    T.Normalize([127.5], [127.5]),\n",
    "])\n",
    "# 数据集定义\n",
    "train_dataset = FashionMNIST(mode='train', transform=transform)\n",
    "val_dataset = FashionMNIST(mode='test', transform=transform)\n",
    "\n",
    "# 模型设置\n",
    "model = paddle.Model(VGG)\n",
    "model.prepare(\n",
    "    paddle.optimizer.Adam(learning_rate=lr, parameters=model.parameters()),\n",
    "    paddle.nn.CrossEntropyLoss(),\n",
    "    paddle.metric.Accuracy(topk=(1, 5)))\n",
    "# 模型训练\n",
    "model.fit(train_dataset, val_dataset, epochs=num_epochs, batch_size=batch_size, log_freq=200)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## 小结\n",
    "\n",
    "* VGG-11 使用可复用的卷积块构造网络。不同的 VGG 模型可通过每个块中卷积层数量和输出通道数量的差异来定义。\n",
    "* 块的使用导致网络定义的非常简洁。使用块可以有效地设计复杂的网络。\n",
    "* 在VGG论文中，Simonyan和Ziserman尝试了各种架构。特别是他们发现深层且窄的卷积（即$3 \\times 3$）比较浅层且宽的卷积更有效。\n",
    "\n",
    "## 练习\n",
    "\n",
    "1. 打印层的尺寸时，我们只看到 8 个结果，而不是 11 个结果。剩余的 3 层信息去哪了？\n",
    "1. 与 AlexNet 相比，VGG 的计算要慢得多，而且它还需要更多的显存。分析出现这种情况的原因。\n",
    "1. 尝试将Fashion-MNIST数据集图像的高度和宽度从 224 改为 96。这对实验有什么影响？\n",
    "1. 请参考 VGG 论文 :cite:`Simonyan.Zisserman.2014` 中的表1构建其他常见模型，如 VGG-16 或 VGG-19。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "[Discussions](https://discuss.d2l.ai/t/1866)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "PaddlePaddle 2.1.0 (Python 3.5)",
   "language": "python",
   "name": "py35-paddle1.2.0"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
